package com.realbrand.net.realbrandpay.ui.activity.wallet.withdraw;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.realbrand.net.realbrandpay.APP;
import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.alipay.AuthResult;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.inter.IAuthorized;
import com.realbrand.net.realbrandpay.inter.ICashWithdrawals;
import com.realbrand.net.realbrandpay.inter.IGetAuthInfo;
import com.realbrand.net.realbrandpay.ui.activity.login.LoginActivity;
import com.realbrand.net.realbrandpay.ui.activity.shopcar.CheckOutActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.WalletActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.order.OrderActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.set.ForgetPayPasswordActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.set.PayVerifyMobileActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.set.WalletLogoutActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.bean.GetAuthCode;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.weight.EditTextJudgeNumberWatcher;
import com.realbrand.net.realbrandpay.weight.PasswordView;
import com.realbrand.net.realbrandpay.zxing.util.L;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/7/3.
 */

public class WithdrawActivity extends BaseActivity {
    @BindView(R.id.withdraw_toolBar)
    Toolbar withdrawToolBar;
    @BindView(R.id.withdraw_tv_WX)
    TextView withdrawTvWX;
    @BindView(R.id.withdraw_tv_WXUnauth)
    TextView withdrawTvWXUnauth;
    @BindView(R.id.withdraw_tv_Alipay)
    TextView withdrawTvAlipay;
    @BindView(R.id.withdraw_tv_AlipayUnauth)
    TextView withdrawTvAlipayUnauth;
    @BindView(R.id.withdraw_et_withdrawMoney)
    EditText withdrawEtWithdrawMoney;
    @BindView(R.id.withdraw_tv_canWithdrawMoney)
    TextView withdrawTvCanWithdrawMoney;
    @BindView(R.id.withdraw_linear_wx)
    LinearLayout withdrawLinearWx;
    @BindView(R.id.withdraw_linear_alipay)
    LinearLayout withdrawLinearAlipay;
    @BindView(R.id.withdraw_bt_withdraw)
    Button withdrawBtWithdraw;
    SharedPreferences preferences;
    //用户名
    public String userName;
    //用户选择了哪种提现方式
    private int whichWithdraw = 1;

    //可提现的金额
    private double canWithDrawMoney;


    public AlertDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        withdrawToolBar.setTitle("");
        withdrawToolBar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(withdrawToolBar);
        withdrawToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(WithdrawActivity.this, WalletActivity.class));
                finish();
            }
        });

        //订阅事件
        EventBus.getDefault().register(this);
        //取出可提现的余额
        preferences = getSharedPreferences("userMassage", MODE_PRIVATE);
        String balance = preferences.getString("balance", "");
        canWithDrawMoney = Double.parseDouble(balance);
        userName = preferences.getString("account", "");
        withdrawTvCanWithdrawMoney.setText("可提现金额" + balance);
        withdrawEtWithdrawMoney.addTextChangedListener(new EditTextJudgeNumberWatcher(withdrawEtWithdrawMoney));
        //根据登录界面的标识判断哪些提现方式以及授权
        String WXAuth = preferences.getString("WXName", "");
        if (!"".equals(WXAuth)) {
            withdrawTvWXUnauth.setText("已授权");
            withdrawTvWX.setText(WXAuth);
        } else {
            withdrawTvWXUnauth.setText("未授权");
            withdrawTvWX.setText("");
        }
        String alipayAuth = preferences.getString("alipayName", "");
        if (!"".equals(alipayAuth)) {
            withdrawTvAlipayUnauth.setText("已授权");
            withdrawTvAlipay.setText(alipayAuth);
        } else {
            withdrawTvAlipayUnauth.setText("未授权");
            withdrawTvAlipay.setText("");
        }
        SpannableString s = new SpannableString("最少提现1元");
        AbsoluteSizeSpan textSize = new AbsoluteSizeSpan(20, true);
        s.setSpan(textSize, 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        withdrawEtWithdrawMoney.setHint(s);
        setOnClick();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.withdraw_activity;
    }

    @Override
    protected void setOnClick() {
        withdrawBtWithdraw.setOnClickListener(this);
        withdrawLinearWx.setOnClickListener(this);
        withdrawLinearAlipay.setOnClickListener(this);
    }

    /**
     * 点击提现
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.withdraw_linear_alipay:
                withdrawLinearWx.setBackgroundColor(getResources().getColor(R.color.color_white));
                whichWithdraw = 2;
                withdrawLinearAlipay.setBackgroundColor(getResources().getColor(R.color.color_select));
                break;
            case R.id.withdraw_linear_wx:
                withdrawLinearAlipay.setBackgroundColor(getResources().getColor(R.color.color_white));
                whichWithdraw = 1;
                withdrawLinearWx.setBackgroundColor(getResources().getColor(R.color.color_select));
                break;
            case R.id.withdraw_bt_withdraw:


//                获取用户输入的提现金额
                String s = withdrawEtWithdrawMoney.getText().toString();
                if (s.equals("")) {
                    Static.toast(this, "请输入提现金额");
                } else {
                    double parseDouble = Double.parseDouble(s);
                    if (new BigDecimal(parseDouble).compareTo(new BigDecimal(1.00)) == -1) {
                        Static.toast(this, "请输入有效金额");
                    } else {
                        //判断用户提现的金额跟账户余额
                        BigDecimal decimal = new BigDecimal(canWithDrawMoney);
                        BigDecimal decimal1 = new BigDecimal(parseDouble);
                        if (decimal.compareTo(decimal1) == -1) {
                            Static.toast(this, "余额不足");
                        } else {
                            switch (whichWithdraw) {
                                //微信
                                case 1:
                                    if (Constant.wx_api.isWXAppInstalled()) {
                                        if (APP.WXIsAuth) {
                                            withDraw(whichWithdraw);
                                        } else {
                                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                                            String date = sdf.format(new Date());
                                            WXAuth(date);
                                        }
                                    } else {
                                        Static.toast(this, "没有安装微信客户端");
                                    }
                                    break;
                                //支付宝
                                case 2:
                                    if (APP.AlipayIsAuth) {
                                        withDraw(whichWithdraw);
                                    } else {
                                        getAutnInfo(whichWithdraw);
                                    }
                                    break;
                                //龙支付
                                case 0:
                                    break;
                                case 3:
                                    Static.toast(this, "请选择提现方式");
                                    break;

                            }
                        }

                    }
                }
                break;
        }


    }

    private void payPassword(final int i) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.pay_password_layout, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Translucent_NoTitle);
        dialog = builder.create();
        dialog.setView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        final PasswordView passwordView = (PasswordView) view.findViewById(R.id.pwd_view);
        passwordView.setOnFinishInput(new PasswordView.OnPasswordInputFinish() {
            @Override
            public void inputFinish() {
                String strPassword = passwordView.getStrPassword();
                try {
                    //获取提现的金额
                    final String withDrawMoney = withdrawEtWithdrawMoney.getText().toString();
                    List<List<String>> withDrawList = new ArrayList<>();
                    List<String> keyList = new ArrayList<>();
                    keyList.add("PaymentMode");
                    keyList.add("UserAccount");
                    keyList.add("DealMoney");
                    keyList.add("DealType");
                    keyList.add("PayPasswd");
                    withDrawList.add(keyList);
                    List<String> valueList = new ArrayList<>();
                    valueList.add(i + "");
                    valueList.add(userName);
                    valueList.add(withDrawMoney);
                    valueList.add("1");
                    valueList.add(strPassword);
                    withDrawList.add(valueList);
                    String encode = URLEncoder.encode(Static.string(withDrawList), "utf-8");
                    JSONObject withDrawJson = new JSONObject();
                    withDrawJson.put("SOURCE", "WithdrawActivity");
                    withDrawJson.put("CREDENTIALS", "0");
                    withDrawJson.put("TERMINAL", "1");
                    withDrawJson.put("INDEX", Static.getDay());
                    withDrawJson.put("METHOD", "CashWithdrawals");
                    withDrawJson.put("DATA", encode);
                    RequestBody body = RequestBody.create(HTTPAPI.JSON, withDrawJson.toString());
                    Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.PAY_BASE_URL).build();
                    ICashWithdrawals iCashWithdrawals = retrofit.create(ICashWithdrawals.class);
                    Call<ResponseBody> call = iCashWithdrawals.cashWithdrawals(body);
                    call.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            try {
                                String withDrawResult = response.body().string();
                                L.d(L.TAG, "提现返回的结果" + withDrawResult);
                                if (withDrawResult.equals("")) {
                                    Static.toast(WithdrawActivity.this, "网络繁忙");
                                } else {
                                    JSONObject object = new JSONObject(withDrawResult);
                                    JSONArray data = object.getJSONArray("DATA");
                                    String dataString = data.getString(0);
                                    if (dataString.equals("0")) {
                                        Static.toast(WithdrawActivity.this, "网络繁忙,提现失败");
                                    } else if (dataString.equals("1")) {
                                        Static.toast(WithdrawActivity.this, "提现成功");
                                        double v1 = Double.parseDouble(withDrawMoney);
                                        Double v = canWithDrawMoney - v1;
                                        DecimalFormat df = new DecimalFormat("0.00");
                                        String format = df.format(v);
                                        SharedPreferences.Editor edit = preferences.edit();
                                        edit.putString("balance", format);
                                        edit.commit();
                                        startActivity(new Intent(WithdrawActivity.this, WalletActivity.class));
                                        finish();
                                    } else if (dataString.equals("2")) {
                                        Static.toast(WithdrawActivity.this, "密码错误");
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        passwordView.getCancelImageView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        passwordView.getForgetTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(WithdrawActivity.this, PayVerifyMobileActivity.class));
                dialog.dismiss();
            }
        });
        dialog.show();

    }

    private void getAutnInfo(final int whichWithdraw) {
        JSONObject authJson = new JSONObject();
        try {
            authJson.put("SOURCE", "WithdrawActivity");
            authJson.put("CREDENTIALS", "0");
            authJson.put("TERMINAL", "1");
            authJson.put("INDEX", Static.getDay());
            authJson.put("METHOD", "Authorized");
            authJson.put("PaymentMode", whichWithdraw);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, authJson.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.PAY_BASE_URL).build();
            IAuthorized iAuthorized = retrofit.create(IAuthorized.class);
            Call<ResponseBody> authorized = iAuthorized.authorized(body);
            authorized.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String string = response.body().string();
                        L.d(L.TAG, "获取授权字符串返回的结果" + string);
                        if (string.equals("")) {
                            Static.toast(WithdrawActivity.this, "网络繁忙");
                        } else {
                            JSONObject jsonObject = new JSONObject(string);
                            JSONArray data = jsonObject.getJSONArray("DATA");
                            String authString = data.getString(0);
                            auth(authString, whichWithdraw);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void auth(String authString, int whichWithdraw) {
        switch (whichWithdraw) {
            //龙支付授权
            case 0:
                break;
            //微信授权
            case 1:
                break;
            //支付宝授权
            case 2:
                alipayAuth(authString);
                break;
        }
    }

    /**
     * 微信调起授权
     *
     * @param authString
     */
    private void WXAuth(String authString) {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = authString;
        Constant.wx_api.sendReq(req);
    }

    private void alipayAuth(final String authString) {
        Runnable authRunnable = new Runnable() {
            @Override
            public void run() {
                AuthTask authTask = new AuthTask(WithdrawActivity.this);
                Map<String, String> result = authTask.authV2(authString, true);
                Message msg = new Message();
                msg.what = CheckOutActivity.SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }


    /**
     * 支付宝支付结果返回
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case CheckOutActivity.SDK_AUTH_FLAG:
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        //获取授权code
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                try {
                                    sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();
                        String authCode = authResult.getAuthCode();
                        getAuthResult(authCode, 2, userName);
                    } else {
                        Static.toast(WithdrawActivity.this, "授权失败");
                    }
                    break;
                case CheckOutActivity.CHANGE_UI_ALIPAY:
                    String string = (String) msg.obj;
                    withdrawTvAlipay.setText(string);
                    withdrawTvAlipayUnauth.setText("已授权");
                    break;
                case CheckOutActivity.CHANGE_UI_WX:
                    String string1 = (String) msg.obj;
                    withdrawTvWX.setText(string1);
                    withdrawTvWXUnauth.setText("已授权");
                    break;
            }
        }
    };

    /**
     * 请求服务器获取授权信息
     *
     * @param authCode 授权code
     * @param i        哪一种支付方式
     */
    public void getAuthResult(String authCode, final int i, String name) {
        try {
            JSONObject getResultjson = new JSONObject();
            getResultjson.put("SOURCE", "WithdrawActivity");
            getResultjson.put("CREDENTIALS", "0");
            getResultjson.put("TERMINAL", "1");
            getResultjson.put("INDEX", Static.getDay());
            getResultjson.put("METHOD", "GetAuthInfo");
            getResultjson.put("PaymentMode", i + "");
            getResultjson.put("AuthCode", authCode);
            getResultjson.put("UserAccount", name);
            L.d(L.TAG, "参数" + getResultjson.toString());
            RequestBody body = RequestBody.create(HTTPAPI.JSON, getResultjson.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.PAY_BASE_URL).build();
            IGetAuthInfo iGetAuthInfo = retrofit.create(IGetAuthInfo.class);
            Call<ResponseBody> authInfo = iGetAuthInfo.getAuthInfo(body);
            authInfo.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String getAuthInfo = response.body().string();
                        L.d(L.TAG, "获取授权成功返回的结果" + getAuthInfo);
                        if (getAuthInfo.equals("")) {
                            Static.toast(WithdrawActivity.this, "网络繁忙");
                        } else {
                            JSONObject getAuthInfoJson = new JSONObject(getAuthInfo);
                            JSONArray data = getAuthInfoJson.getJSONArray("DATA");
                            if (data.getJSONObject(0).getString("user_id").equals("")) {
                                Static.toast(WithdrawActivity.this, "授权失败");
                            } else {
                                //表示授权成功
                                JSONObject object = data.getJSONObject(0);
                                String name = object.getString("nick_name");
                                Message message = new Message();
                                if (i == 2) {
                                    message.what = CheckOutActivity.CHANGE_UI_ALIPAY;
                                    message.obj = name;
                                    mHandler.sendMessage(message);
                                    APP.AlipayIsAuth = true;
                                    SharedPreferences.Editor edit = preferences.edit();
                                    edit.putString("alipayName", name);
                                    edit.commit();
                                    //提现
                                    withDraw(i);
                                } else if (i == 1) {
                                    message.what = CheckOutActivity.CHANGE_UI_WX;
                                    message.obj = name;
                                    mHandler.sendMessage(message);
                                    APP.WXIsAuth = true;
                                    SharedPreferences.Editor edit = preferences.edit();
                                    edit.putString("WXName", name);
                                    edit.commit();
                                    //提现
                                    withDraw(i);
                                }
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        L.d(L.TAG, "异常" + e.toString());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void withDraw(final int i) {
        payPassword(i);

    }

    @Subscribe          //订阅事件FirstEvent
    public void onEventMainThread(GetAuthCode code) {
        getAuthResult(code.getCode(), 1, userName);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //返回事件
            startActivity(new Intent(this, WithdrawActivity.class));
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
